package com.leruan.aasimp.action.usedcar;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.leruan.aasimp.bean.UsedCarSaleMainBean;
import com.leruan.aasimp.constant.UsedCarConstant;
import com.leruan.aasimp.entity.CarBasicInfo;
import com.leruan.aasimp.entity.CarSaleImage;
import com.leruan.aasimp.entity.Eauser;
import com.leruan.aasimp.entity.UsedCarSale;
import com.leruan.aasimp.service.BasicCarService;
import com.leruan.aasimp.service.EauserService;
import com.leruan.aasimp.service.UsedCarService;
import com.leruan.aasimp.util.SecurityUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ViewSaleUsedCar extends ActionSupport {

	private static final long serialVersionUID = 1539517044673446619L;

	@Resource
	private UsedCarService usedCarService;
	@Resource
	private BasicCarService basicCarService;
	@Resource
	private EauserService eauserService;
	
	public String show() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			int pageNo = 1;
			String req_no = request.getParameter("no");
			if(req_no != null)
				pageNo = Integer.parseInt(req_no);
			
			List<String> brandList = basicCarService.getBrandList();
			List<String> departmentList = new ArrayList<String>();
			
			request.setAttribute("isBrand", 0);
			String req_brand = request.getParameter("brand");
			int i = 0;
			if(req_brand != null & !"".equals(req_brand)){
				String brand = new String(req_brand.getBytes("iso-8859-1"), "UTF-8");
				map.put("brand", brand);
				request.setAttribute("brand1", brand);
				request.setAttribute("isBrand", 1);
				departmentList = basicCarService.getDepartmentListByBrand(brand);
				if(session.getAttribute("brandOld")==null | brand.equals(session.getAttribute("brandOld")))
					i = 1;
				session.setAttribute("brandOld", brand);
			}
			
			request.setAttribute("isDepartment", 0);
			String req_department = request.getParameter("department");
			if(req_department != null & !"".equals(req_department) & i == 1){
				String department = new String(req_department.getBytes("iso-8859-1"), "UTF-8");
				map.put("department", department);
				request.setAttribute("department1", department);
				request.setAttribute("isDepartment", 1);		
			}
			
			request.setAttribute("isPrice", 0);
			String req_price = request.getParameter("price");
			if(req_price != null & !"".equals(req_price)){
				String price = new String(req_price.getBytes("iso-8859-1"), "UTF-8");
				map = UsedCarConstant.convertPrice(map, price);
				request.setAttribute("price1", price);
				request.setAttribute("isPrice", 1);
			}
			request.setAttribute("isCarYear", 0);
			String req_CarYear = request.getParameter("carYear");
			if(req_CarYear != null & !"".equals(req_CarYear)){
				String carYear = new String(req_CarYear.getBytes("iso-8859-1"), "UTF-8");
				map = UsedCarConstant.convertCarYear(map, carYear);
				request.setAttribute("carYear1", carYear);
				request.setAttribute("isCarYear", 1);
			}
			
			request.setAttribute("brandList", brandList);
			request.setAttribute("departmentList", departmentList);
			request.setAttribute("priceList", UsedCarConstant.priceList);
			request.setAttribute("carYearList", UsedCarConstant.carYearList);
			
			List<UsedCarSaleMainBean> usedCarList = usedCarService.getUsedCarSaleList(map, pageNo);
			Long total = usedCarService.getUsedSaleTotal(map);
			request.setAttribute("usedCarSaleList", usedCarList);
			request.setAttribute("pageNoSale", pageNo);
			request.setAttribute("pageNoCenterSale", 3);
			Long totalNo = total / UsedCarConstant.PAGE_SIZE + 1;
			request.setAttribute("totalNoSale", totalNo);
			request.setAttribute("totalSale", total);
			if (pageNo < 3 || totalNo < 5) {
				request.setAttribute("pageNoCenterSale", 3);
			} else if (pageNo > totalNo - 2) {
				request.setAttribute("pageNoCenterSale", totalNo - 2);
			} else {
				request.setAttribute("pageNoCenterSale", pageNo);
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return "show";
	}
	
	public String showMyUsedCarSale(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		try {
			Eauser eauser = (Eauser) session.getAttribute("eauser");
			System.out.println(eauser.getUserId());
			List<UsedCarSaleMainBean> usedCarList = usedCarService.getUsedCarSaleListById(eauser.getUserId());
			request.setAttribute("usedCarSaleList", usedCarList);
			if(usedCarList.size() == 0)
				request.setAttribute("size", 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "myUsedCarSaleInfo";
	}
	
	public String deleteMyUsedCarSale(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String id = request.getParameter("id");
		
		Eauser eauser = (Eauser) session.getAttribute("eauser");
		try {
			usedCarService.deleteMyUsedCarSale(id, eauser.getUserId());
			request.setAttribute("isDelete", 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return showMyUsedCarSale();
	}
	
	public String add() {
		HttpServletRequest request = ServletActionContext.getRequest();
		
		try {
			List<String> brandList = basicCarService.getBrandList();
			request.setAttribute("brands", brandList);
			
			Date date = new Date();
			StringBuffer buyDate = new StringBuffer(date.getYear()+1900+"");
			if(date.getMonth() < 9)
				buyDate.append("-0" + (date.getMonth()+1));
			else
				buyDate.append("-" + (date.getMonth()+1));
			if(date.getDate() < 10)
				buyDate.append("-0" + date.getDate());
			else
				buyDate.append("-" + date.getDate());
			request.setAttribute("buyDate", buyDate);
			request.setAttribute("annualDate", buyDate);
			request.setAttribute("compulsoryDate", buyDate);
			System.out.println(buyDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "add";
	}

	public String save(){
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			
			String brand = request.getParameter("brand");
			String department = request.getParameter("department");
			String carType = request.getParameter("carType");
			String mileage = request.getParameter("mileage");
			String money = request.getParameter("money");
			String intro = request.getParameter("intro");
			String color = request.getParameter("color");
			String buyDate = request.getParameter("buyDate");
			String content = request.getParameter("content");
			String name = request.getParameter("name");
			String telephone = request.getParameter("telephone");
			String isMaintain = request.getParameter("isMaintain");
			String isAccident = request.getParameter("isAccident");
			String isAppearance = request.getParameter("isAppearance");
			String isInterior = request.getParameter("isInterior");
			String isCertificate = request.getParameter("isCertificate");
			String annualDate = request.getParameter("annualDate");
			String compulsoryDate = request.getParameter("compulsoryDate");
			
			Long carBasicId = basicCarService.getCarBasicId(brand, department, carType);

			UsedCarSale usedCarSale = new UsedCarSale();
			
			usedCarSale.setCarBasicId(carBasicId);
			usedCarSale.setTitle(brand + department + " " + carType);
			usedCarSale.setIntro(intro);
			HttpSession session = request.getSession();
			
			Eauser eauser = (Eauser) session.getAttribute("eauser");
			
			usedCarSale.setUserId(eauser.getUserId());
			usedCarSale.setName(name);
			usedCarSale.setTelephone(Long.parseLong(telephone));
			usedCarSale.setType(Long.parseLong("1"));
			usedCarSale.setContent(content);
			usedCarSale.setReleaseTime(new Date());
			usedCarSale.setBrowseNum(Long.parseLong("0"));
			usedCarSale.setColor(color);
			usedCarSale.setBuyDate(java.sql.Date.valueOf(buyDate));
			usedCarSale.setMileage(mileage);
			usedCarSale.setMoney(money);
			usedCarSale.setIsMaintain(Long.parseLong(isMaintain));
			usedCarSale.setIsAccident(Long.parseLong(isAccident));
			usedCarSale.setIsAppearance(Long.parseLong(isAppearance));
			usedCarSale.setIsInterior(Long.parseLong(isInterior));
			usedCarSale.setIsCertificate(Long.parseLong(isCertificate));
			usedCarSale.setAnnualDate(java.sql.Date.valueOf(annualDate));
			usedCarSale.setCompulsoryDate(java.sql.Date.valueOf(compulsoryDate));
			usedCarSale.setStatus(Long.parseLong("1"));
			usedCarSale.setMainImg("../img/saleImg/10086.jpg");
			
			usedCarService.saveUsedCarSale(usedCarSale);
//			Long id = usedCarService.findId(usedCarSale);
			
			CarSaleImage carSaleImage = new CarSaleImage();
			carSaleImage.setCarSaleId(usedCarSale.getId());
			carSaleImage.setImageAddress("../img/saleImg/10086.jpg");
			usedCarService.saveImage(carSaleImage);
			carSaleImage.setImageAddress("../img/saleImg/10087.jpg");
			usedCarService.saveImage(carSaleImage);
			
			List<String> brandList = basicCarService.getBrandList();
			List<String> departmentList = new ArrayList<String>();
			int pageNo = 1;
			request.setAttribute("brandList", brandList);
			request.setAttribute("departmentList", departmentList);
			request.setAttribute("priceList", UsedCarConstant.priceList);
			request.setAttribute("carYearList", UsedCarConstant.carYearList);
			
			Map<String, Object> map = new HashMap<String, Object>();
			
			List<UsedCarSaleMainBean> usedCarList = usedCarService.getUsedCarSaleList(map, pageNo);
			Long total = usedCarService.getUsedSaleTotal(map);
			request.setAttribute("usedCarSaleList", usedCarList);
			request.setAttribute("pageNoSale", pageNo);
			request.setAttribute("pageNoCenterSale", 3);
			Long totalNo = total / UsedCarConstant.PAGE_SIZE + 1;
			request.setAttribute("totalNoSale", totalNo);
			request.setAttribute("totalSale", total);
			if (pageNo < 3 || totalNo < 5) {
				request.setAttribute("pageNoCenterSale", 3);
			} else if (pageNo > totalNo - 2) {
				request.setAttribute("pageNoCenterSale", totalNo - 2);
			} else {
				request.setAttribute("pageNoCenterSale", pageNo);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "show";
	}
	
	public String showSaleInfo() {

		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("id", request.getParameter("id"));
		return "showInfo";
	}

	public String showDetail() {

		HttpServletRequest request = ServletActionContext.getRequest();
		String id = request.getParameter("id");
		try {
			UsedCarSale usedCarSale = usedCarService.getUsedCarSaleById(id);
			request.setAttribute("usedCarSale", usedCarSale);
			
			CarBasicInfo carBasicInfo = basicCarService.getCarBasicInfoById(usedCarSale.getCarBasicId().toString());
			request.setAttribute("carBasicInfo", carBasicInfo);
			
			List<String> imagesUrl = usedCarService.getImagesUrlById(id);
			request.setAttribute("imagesUrl", imagesUrl);
			usedCarSale.setBrowseNum(usedCarSale.getBrowseNum() + 1);
			usedCarService.updateUsedCarSale(usedCarSale);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "showDetail";

	}
	
	
	
	public String logout() {
		ActionContext context = ServletActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context
				.get(ServletActionContext.HTTP_REQUEST);
		request.getSession().removeAttribute("eauser");
		return "index";
	}
	
	public String login() {
		ActionContext context = ServletActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context
				.get(ServletActionContext.HTTP_REQUEST);
		String username = request.getParameter("username").trim();
		String password = request.getParameter("password");

		Eauser eauser = eauserService.getEauserByUn(username);
		if (eauser == null) {
			request.setAttribute("message", "用户名不存在！");
			return "login";
		}
		String pwd = SecurityUtils.encodeByMD5(password);
			
		if (eauser.getPassword().equals(pwd)) {
			request.getSession().setAttribute("eauser", eauser);
		} else {
			request.setAttribute("message", "密码输入有误！");
		}
		return "login";
	}
	
	public void setUsedCarService(UsedCarService usedCarService) {
		this.usedCarService = usedCarService;
	}

	public void setBasicCarService(BasicCarService basicCarService) {
		this.basicCarService = basicCarService;
	}

	public void setEauserService(EauserService eauserService) {
		this.eauserService = eauserService;
	}

}
